package plugin

import (
	"github.com/rock-rabbit/rain"
	"time"
	"wf-deploy-agent/infra"
)

func NewLoader() *Loader {
	return &Loader{
		BasePlugin: &BasePlugin{Name: "loader"},
	}
}

type Loader struct {
	*BasePlugin
}

func (l *Loader) Download(origin string, dir, filename string, speed int) error {
	//util.Acquire(l.getFileName()).Lock()
	//bytes, err := util.Exec(l.getFilePath(), "-o", origin, "-d", dir, "-f", filename, "-s", strconv.Itoa(speed))
	//util.Acquire(l.getFileName()).Unlock()
	//return string(bytes), err

	infra.Logger.Infof("[%s]下载开始", origin)
	ctl, err := rain.New(origin,
		rain.WithOutdir(dir),
		rain.WithCreateDir(true),
		rain.WithOutname(filename),
		rain.WithSpeedLimit(speed*(1024<<10)),
		rain.WithRetryTime(time.Duration(3)*time.Second),
		rain.WithAllowOverwrite(true)).Run()

	defer func() {
		if ctl.Status() == rain.STATUS_FINISH {
			infra.Logger.Infof("[%s]下载完成", origin)
		}
	}()

	if err != nil {
		infra.Logger.Errorf("[%s]下载出错，%v", origin, err)
		return err
	}

	return nil
}
